package com.hxzy.service.impl;

import cn.hutool.json.JSONUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.hxzy.common.constants.MarketConstants;
import com.hxzy.common.enums.AckCode;
import com.hxzy.common.exception.ServiceException;
import com.hxzy.common.resp.DishFlavorItem;
import com.hxzy.common.resp.DishFlavorItemProp;
import com.hxzy.common.util.MarketThreadLocalUtil;
import com.hxzy.controller.admin.login.resp.AdminLoginResp;
import com.hxzy.controller.admin.product.req.*;
import com.hxzy.controller.admin.product.resp.ProductResp;
import com.hxzy.controller.mobile.product.req.MobileProductReq;
import com.hxzy.controller.mobile.product.resp.MobileProductResp;
import com.hxzy.entity.DishFlavor;
import com.hxzy.entity.Product;
import com.hxzy.mapstruct.ProductMapStruct;
import com.hxzy.service.DishFlavorService;
import com.hxzy.service.ProductService;
import com.hxzy.mapper.ProductMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Objects;

/**
* @author admin
* @description 针对表【product(商品信息)】的数据库操作Service实现
* @createDate 2024-02-21 11:30:41
*/
@Service
public class ProductServiceImpl extends ServiceImpl<ProductMapper, Product>
    implements ProductService{

    /**
     * 规格业务逻辑
     */
    @Autowired
    private DishFlavorService  dishFlavorService;

    @Override
    public List<ProductResp> search(ProductSearchReq req) {
        AdminLoginResp adminLoginResp = MarketThreadLocalUtil.ADMIN_THREAD_LOCAL.get();
        //商家只允许赋值自己的
        if(MarketConstants.ACCOUNT_MERCHANDISER_TYPE.equals(adminLoginResp.getPermissions())){
            req.setMerchandId(adminLoginResp.getId());
        }

        // product -- category_class-->  merchandiser  三张表
        List<ProductResp> list = this.baseMapper.search(req);
        //自己定义组装商品规格
        list.forEach(this::searchDishFlavorItem);
        return list;
 
    }

    @Transactional(rollbackFor = Exception.class)
    @Override
    public boolean addData(ProductAddReq req) {
        AdminLoginResp adminLoginResp = MarketThreadLocalUtil.ADMIN_THREAD_LOCAL.get();

        Product entity = ProductMapStruct.INSTANCE.convert(req);
        entity.setMerchantId(adminLoginResp.getId());
        entity.setCreateBy(adminLoginResp.getName());
        entity.setCreateTime(new Date());
        entity.setUpdateTime(new Date());
        this.save(entity);

        //新增明细
        return insertBatchDishFlash(entity.getId(), req.getDishFlavors());
    }

    @Override
    public ProductResp findById(Long id) {
        Product db = this.getById(id);
        if(Objects.isNull(db)){
            throw new ServiceException(AckCode.NOT_FOUND_DATA);
        }

        ProductResp convert = ProductMapStruct.INSTANCE.convert(db);

        //商品规格
        searchDishFlavorItem(convert);
        return convert;
    }

    /**
     * 商品规格查询
     * @param convert
     */
    private void searchDishFlavorItem(ProductResp convert) {
        List<DishFlavorItem>  flavorList=new ArrayList<>();
        LambdaQueryWrapper<DishFlavor> queryWrapper=new LambdaQueryWrapper<>();
        queryWrapper.eq(DishFlavor::getDishId, convert.getId());
        queryWrapper.orderByAsc(DishFlavor::getId);
        //查询商品规格
        List<DishFlavor> dishFlavorList = this.dishFlavorService.list(queryWrapper);

        dishFlavorList.forEach( s ->{
            DishFlavorItem  di=new DishFlavorItem();
            di.setName(s.getName());
            //json反序列化
            di.setValue(JSONUtil.toList(s.getValue(), DishFlavorItemProp.class));
            //放到自定义集合中
            flavorList.add(di);
        });
        //赋值自定义商品规格
        convert.setDishFlavors(flavorList);
    }

    @Transactional(rollbackFor = Exception.class)
    @Override
    public boolean updateData(ProductEditReq req) {
        AdminLoginResp adminLoginResp = MarketThreadLocalUtil.ADMIN_THREAD_LOCAL.get();

        Product db = this.getById(req.getId());
        if(Objects.isNull(db)){
            throw new ServiceException(AckCode.NOT_FOUND_DATA);
        }
        //不允许修改其它商家的商品数据
        if(!db.getMerchantId().equals(adminLoginResp.getId())){
            throw new ServiceException(AckCode.NOT_MODIFY_OTHER_USER);
        }

        Product entity = ProductMapStruct.INSTANCE.convert(req);
        entity.setUpdateBy(adminLoginResp.getName());
        entity.setUpdateTime(new Date());
        this.updateById(entity);

        //删除商品规格
        LambdaQueryWrapper<DishFlavor> queryWrapper=new LambdaQueryWrapper<>();
        queryWrapper.eq(DishFlavor::getDishId,req.getId());
        this.dishFlavorService.remove(queryWrapper);

        //重新增加数据
        //新增商品明细
        return insertBatchDishFlash( db.getId(), req.getDishFlavors());
    }

    @Override
    public boolean upOrDown(ProductUpOrDownReq req) {
        AdminLoginResp adminLoginResp = MarketThreadLocalUtil.ADMIN_THREAD_LOCAL.get();
        //先判断是否是该商家的数据
        if(adminLoginResp.getId().longValue()!=req.getMerchantId().longValue()){
            throw new ServiceException(AckCode.PERMISSION_NOT_ACCESS_CATEGORY);
        }

        Product db = this.getById(req.getId());
        if(Objects.isNull(db)){
            throw new ServiceException(AckCode.NOT_FOUND_DATA);
        }

        //只更新某一列getIsgrounding
        Product entity=new Product();
        entity.setId(req.getId());
        entity.setIsgrounding(req.getIsgrounding());
        entity.setUpdateTime(new Date());
        entity.setUpdateBy(adminLoginResp.getName());

        return this.updateById(entity);
    }

    @Override
    public boolean changeStock(ProductStockChangeReq req) {
        AdminLoginResp adminLoginResp = MarketThreadLocalUtil.ADMIN_THREAD_LOCAL.get();
        //先判断是否是该商家的数据
        if(adminLoginResp.getId().longValue()!=req.getMerchantId().longValue()){
            throw new ServiceException(AckCode.PERMISSION_NOT_ACCESS_CATEGORY);
        }
        if(req.getNum()<-1){
            throw new ServiceException(AckCode.PRODUCT_STOCK_ERROR);
        }
        Product product=new Product();
        product.setId(req.getId());
        product.setNum(req.getNum());
        product.setUpdateTime(new Date());
        product.setUpdateBy( adminLoginResp.getName());
        return this.updateById(product);
    }

    @Override
    public boolean batchDown(Long[] ids) {
        AdminLoginResp adminLoginResp = MarketThreadLocalUtil.ADMIN_THREAD_LOCAL.get();
        //先判断是否是该商家的数据
        long currentId=adminLoginResp.getId();
        LambdaQueryWrapper<Product> queryWrapper=new LambdaQueryWrapper<>();
        queryWrapper.in(Product::getId,ids);
        queryWrapper.eq(Product::getMerchantId,currentId);
        long count = this.count(queryWrapper);
        //有些商品不是这个商家的
        if(count!=ids.length){
            throw new ServiceException(AckCode.PERMISSION_NOT_ACCESS_CATEGORY);
        }

        //构建一个集合
        List<Product>  list=new ArrayList<>();
        for(long  id : ids){
            Product  product=new Product();
            product.setId(id);
            product.setIsgrounding(MarketConstants.ACCOUT_ENABLE);
            product.setUpdateTime(new Date());
            product.setUpdateBy( adminLoginResp.getName());
            list.add(product);
        }
        return this.saveOrUpdateBatch(list);
    }

    /**
     * 商品信息
     * @param req
     * @return
     */
    @Override
    public List<MobileProductResp> mobileSearch(MobileProductReq req) {
        List<MobileProductResp> mobileProductResps = this.baseMapper.mobileSearch(req);

        //查询商品规格
        mobileProductResps.forEach(this::mobileProductRespDishFlavorItem);

        return mobileProductResps;
    }

    /**
     * 扣库存
     * @param buyNumber
     * @param productDb
     * @return
     */
    @Override
    public long deduceNum(Integer buyNumber, Product productDb) {
        return this.baseMapper.deduceNum(buyNumber,productDb);
    }

    /**
     * 商品规格查询
     * @param convert
     */
    private void mobileProductRespDishFlavorItem(MobileProductResp convert) {
        List<DishFlavorItem>  flavorList=new ArrayList<>();
        LambdaQueryWrapper<DishFlavor> queryWrapper=new LambdaQueryWrapper<>();
        queryWrapper.eq(DishFlavor::getDishId, convert.getId());
        queryWrapper.orderByAsc(DishFlavor::getId);
        //查询商品规格
        List<DishFlavor> dishFlavorList = this.dishFlavorService.list(queryWrapper);

        dishFlavorList.forEach( s ->{
            DishFlavorItem  di=new DishFlavorItem();
            di.setName(s.getName());
            //json反序列化
            di.setValue(JSONUtil.toList(s.getValue(), DishFlavorItemProp.class));
            //放到自定义集合中
            flavorList.add(di);
        });
        //赋值自定义商品规格
        convert.setDishFlavors(flavorList);
    }


    /**
     * 新增商品明细
     * @param productId
     * @param dishFlavors
     * @return
     */
    private boolean insertBatchDishFlash(Long productId, List<DishFlavorItem> dishFlavors) {
        if(Objects.nonNull(dishFlavors) && !dishFlavors.isEmpty()){
            List<DishFlavor>  arr=new ArrayList<>();
            dishFlavors.forEach(p-> {
                DishFlavor  df=new DishFlavor();
                //商品id
                df.setDishId(productId);
                df.setName(p.getName());
                df.setValue(JSONUtil.toJsonStr(p.getValue()));
                df.setIsDeleted(MarketConstants.ACCOUT_ENABLE);
                df.setCreateBy(MarketThreadLocalUtil.ADMIN_THREAD_LOCAL.get().getName());
                df.setCreateTime(new Date());
                arr.add(df);
            });
            this.dishFlavorService.saveBatch(arr);
        }
        return true;
    }
}




